package cn.ezios.huo.core.mvc;

import cn.dev33.satoken.exception.SaTokenException;
import cn.ezios.huo.common.mvc.Ret;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Ret> handleException(Exception e) {
        Ret error = Ret.error(e.getMessage());
//        e.printStackTrace();
        log.error("全局异常捕获:",e);
        if(e instanceof SaTokenException){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Ret.error(e.getMessage()));
        }
        return ResponseEntity.badRequest().body(error);
    }

    @PostConstruct
    public void init() {
        log.info("[{}]{}","控制器异常捕获Advice",this.getClass().getName());
    }
}
